<template>
    <view class="page">
        <view class="tab">
            <view class="item" :class="{ actived: loginIndex == i }" v-for="(item, i) in list" :key="item.name"
                @click="change(i)">
                {{ item.name }}
                <view class="gap" v-if="loginIndex == i"></view>
            </view>
        </view>
        <view class="container">
            <view class="loginForm">

                <view class="form-item">
                    <view class="phone" @click="showPicker" v-if="loginIndex == 0">
                        <text>{{ loginForm.code }}</text>
                        <uv-icon name="arrow-down" color="#fff" size="12"></uv-icon>
                    </view>
                    <input class="form-input" v-model="loginForm.username" placeholder="请输入手机号" />
                </view>

                <view class="checkcode-item" v-if="loginIndex == 0">
                    <view class="form-item checkcode">
                        <input class="form-input" v-model="loginForm.checkcode" placeholder="请输入验证码" />
                    </view>

                    <view v-if="isActive && remainingTime === 60" class="sms-btn" @click="getSmsCode">
                        获取验证码</view>
                    <view v-if="isActive && remainingTime < 60" class="sms-btn disabled">
                        {{ remainingTime }}秒后重新获取
                    </view>
                    <view v-if="!isActive" class="sms-btn" @click="getSmsCode">获取验证码</view>
                </view>

                <view class="form-item" v-if="loginIndex == 1">
                    <input class="form-input" password v-model="loginForm.password" placeholder="请输入密码" />
                </view>

                <view class="accept-item">
                    <view class="selected" :class="{ actived: loginForm.selected }"
                        @click="loginForm.selected = !loginForm.selected">
                    </view>
                    <view class="red">
                        <text class="read-text" @click="loginForm.selected = !loginForm.selected">阅读并接受</text>
                        <navigator class="read-url" open-type="navigate" url="/pages/agreement/agreement">《用户协议》
                        </navigator>
                        <navigator class="read-url" open-type="navigate" url="/pages/privacy/privacy">《隐私政策》</navigator>
                    </view>

                    <navigator v-if="loginIndex == 1" class="reset" url="/pages/resetPassword/resetPassword"
                        hover-class="none" open-type="navigate">
                        忘记密码</navigator>
                </view>
            </view>

            <view class="work-btn-style login" @click="login">登录</view>

        </view>
        <view class="tip">
            <text class="tip-text">未有账号？</text>
            <navigator class="tip-url" url="/pages/register/register" hover-class="none" open-type="redirect">注册账号
            </navigator>
        </view>

        <uv-picker ref="picker" :columns="countryCode" keyName="chinese" @confirm="confirm"></uv-picker>

    </view>
</template>

<script setup>
import {
    ref
} from 'vue';
import {
    onLoad
} from '@dcloudio/uni-app'
//api
import {
    apiSmsSend,
    apiLoginApi,
    apiGetUserInfo,
    apiCountrycode
} from '@/api/authApi.js'

// pinia
import {
    storeToRefs
} from 'pinia'
import {
    useUserStore
} from "@/stores/useUserStore.js"

import {
    useRegisterStore
} from "@/stores/useRegisterMessStore.js"

// 获取pinia的数据
const registerStore = useRegisterStore()

// 获取pinia的数据
const userStore = useUserStore()

// 从pinia的数据中结构出值并做响应式
const {
    token
} = storeToRefs(userStore)

//hooks
import useSmsCountdown from '../../hooks/useCountDown.js';
const {
    remainingTime,
    isActive,
    startCountdown,
    resetCountdown
} = useSmsCountdown(60);


const list = [{
    name: '手机号登录'
}, {
    name: '密码登录'
}]
// 登录方式
const loginIndex = ref(0)

// 手机验证码登录表单
const loginForm = ref({
    authType: 'sms',
    code:'+86'
})
const countryCode = ref([])
const picker = ref(null)




// 切换方式
const change = (i) => {
    loginIndex.value = i
}

//获取验证码
const getSmsCode = async () => {
    // 重置定时器
    resetCountdown()

    //判断手机号
    if (uni.$uv.trim(loginForm.value.username) == '') {
        uni.showToast({
            title: '手机号不能为空',
            icon: "none"
        })
        return
    }

    // 获取短信
    await apiSmsSend({
        cellphone: loginForm.value.username,
        type: 'login'
    })

    // 开启倒计时
    startCountdown()

}

// 登录
const login = () => {
    switch (loginIndex.value) {
        // 手机验证码
        case 0:
            if (uni.$uv.trim(loginForm.value.username) == '') {
                uni.showToast({
                    title: '手机号不能为空',
                    icon: "none"
                })
                return
            }
            if (uni.$uv.trim(loginForm.value.checkcode) == '') {
                uni.showToast({
                    title: '请输入收到的验证码',
                    icon: "none"
                })
                return
            }
            loginForm.value.authType = 'sms'
            break;
        // 账号密码
        case 1:
            if (uni.$uv.trim(loginForm.value.username) == '') {
                uni.showToast({
                    title: '请输入账号',
                    icon: "none"
                })
                return
            }
            if (uni.$uv.trim(loginForm.value.password) == '') {
                uni.showToast({
                    title: '请输入密码',
                    icon: "none"
                })
                return
            }
            loginForm.value.authType = 'password'
            break;
    }

    if (!loginForm.value.selected) {
        uni.showToast({
            title: '请先阅读并同意用户协议，隐私政策',
            icon: "none"
        })
        return
    }

    submitForm(loginForm.value)
}

// 提交表单
const submitForm = async (form) => {
    let res = await apiLoginApi(form)
    userStore.setToken(res.data.access_token)
    registerStore.setRegisterMess({})
    getUserInfo()
}

// 获取用户信息
const getUserInfo = async () => {
    let res = await apiGetUserInfo()

    userStore.setUser(res.data)

    uni.showToast({
        title: '登录成功！',
        icon: "none"
    })

    let pages = getCurrentPages();
    let beforePage = pages[pages.length - 2]; // 上一页
    //调用上一页的生命周期函数

    let urls = ['/pages/index/index', '/pages/draw/draw', '/pages/user/user']

    // console.log(urls,beforePage);

    // if (beforePage) {
    //     uni.navigateBack({
    //         delta: 1,
    //         success: res => {
    //             beforePage.$vm.$.exposed.getModelList ? beforePage.$vm.$.exposed.getModelList() : ''
    //         }
    //     }, 1500)

    // } else {
    uni.switchTab({
        url: '/pages/user/user',
        success: res => {
            beforePage.$vm.$.exposed.getModelList ? beforePage.$vm.$.exposed.getModelList() : ''
        }
    })
    // }


}

//获取全世界国家的手机号码前缀
const getCountrycode = async () => {
    let res = await apiCountrycode()
    countryCode.value[0] = res.data
}

// 弹出手机前缀选择
const showPicker = () => {
    picker.value.open()
    console.log(countryCode.value);
}

// 选择手机前缀
const confirm = (e) => {
    resetForm.value.code = e.value[0].code
}

onLoad(() => {
    getCountrycode()
})
</script>

<style lang="scss" scoped>
.page {
    background: #1a1a1a;
    height: 100vh;
    width: 100vw;
}

.tab {
    width: 100%;
    display: flex;
    justify-content: space-around;
    margin: 100rpx auto 80rpx;

    .item {
        height: 92rpx;
        display: flex;
        align-items: center;
        position: relative;
        color: #999999;
        font-size: 32rpx;

        &.actived {
            color: #fff;
        }

        .gap {
            height: 8rpx;
            background: #ffcb30;
            border-radius: 4rpx;
            width: 100%;
            position: absolute;
            bottom: 0;
        }
    }
}

.container {
    width: 622rpx;
    margin: 0 auto;

    .loginForm {
        width: 100%;

        .checkcode-item {
            margin-bottom: 40rpx;
            width: 622rpx;
            height: 80rpx;
            display: flex;
            justify-content: space-between;
        }

        .form-item {
            margin-bottom: 40rpx;
            width: 622rpx;
            height: 80rpx;
            background: #000000;
            border: 2rpx solid #4d4d4d;
            border-radius: 10rpx;
            padding: 0 30rpx;
            box-sizing: border-box;
            display: flex;
            align-items: center;

            .phone {
                color: #fff;
                font-size: 24rpx;
                font-weight: 500;
                margin-right: 16rpx;
                display: flex;
                flex-direction: row;
            }

            .form-input {
                font-size: 24rpx;
                color: #999;
                flex: 1;
            }

            &.checkcode {
                width: 374rpx;
            }

        }

        .sms-btn {
            width: 232rpx;
            height: 80rpx;
            background: #e6e6e6;
            border-radius: 10rpx;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24rpx;
            color: #000;
            font-weight: 500;

            &.disabled {
                background: #999;
            }
        }

        .accept-item {
            height: 40rpx;
            width: 622rpx;
            display: flex;
            flex-direction: row;
            position: relative;

            .selected {
                width: 40rpx;
                height: 40rpx;
                background: #000000;
                border: 2rpx solid #999999;
                border-radius: 50%;
                position: relative;
                box-sizing: border-box;
                margin-right: 16rpx;

                &.actived {
                    &::after {
                        width: 20rpx;
                        height: 20rpx;
                        background: #ffcb30;
                        content: '';
                        position: absolute;
                        border-radius: 50%;
                        top: 8rpx;
                        left: 8rpx;
                    }
                }
            }

            .red {
                font-size: 24rpx;
                color: #999;
                font-weight: 500;
                display: flex;

                .read-text {
                    margin-right: 20rpx;
                }

                .read-url {
                    color: #FFCB30;
                }
            }

            .reset {
                font-size: 24rpx;
                color: #999;
                font-weight: 500;
                position: absolute;
                right: 0;
            }
        }
    }

    .login {
        height: 96rpx;
        border-radius: 48rpx;
        margin-top: 80rpx;
        font-size: 32rpx;
        color: #000;
        font-weight: 500;
    }
}

.tip {
    width: 100%;
    font-size: 28rpx;
    height: 30rpx;
    line-height: 30rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    position: fixed;
    bottom: 80rpx;
    margin: auto;
    left: 0;

    .tip-text {
        color: #ccc;
    }

    .tip-url {
        color: #fff;
        font-weight: 700;
    }
}
</style>